package com.apps.ftapp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apps.ftapp.R;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.ScreenUtils;
import com.duobeiyun.util.EncryptUtils;

import java.lang.reflect.InvocationTargetException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DefPlaybackActivity extends BaseActivity {
    @BindView(R.id.back_lin)
    LinearLayout back_lin;

    private static final String OPENURL = "open_url";
    private WebView mWebView;
    String timestamp = String.valueOf(System.currentTimeMillis());
    String baseUrl = "http://api.duobeiyun.com/api/v3/room/enter?";
    String appKey;
    String nickname;
    String partner;
    String roomId;
    String uid;
    String sign;
    String url;
    String userRole = "2";
    private String title;
    private Button plback;

    private WebSettings settings;
    private TextView tvclassTitle;


    /**
     * 视频全屏参数
     */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;

    public DefPlaybackActivity() {

    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_def_playback);
        ButterKnife.bind(this);

        this.getWindow().addFlags(128);
        Intent intent = this.getIntent();
        quanping.setVisibility(View.VISIBLE);
        commTitle.setText(intent.getStringExtra("title"));
        if (intent != null) {
            String purl = intent.getStringExtra("open_url");
            if (purl != null) {
                this.url = purl;
            } else {
                this.appKey = intent.getStringExtra("appKey") != null ? intent.getStringExtra("appKey") : "";
                this.nickname = intent.getStringExtra("nickname") != null ? intent.getStringExtra("nickname") : "";
                this.partner = intent.getStringExtra("partner") != null ? intent.getStringExtra("partner") : "";
                this.roomId = intent.getStringExtra("roomId") != null ? intent.getStringExtra("roomId") : "";
                this.uid = intent.getStringExtra("uid") != null ? intent.getStringExtra("uid") : "";
                this.title = intent.getStringExtra("title") != null ? intent.getStringExtra("title") : "在线回放";
                this.generateUrl();
            }
        } else {
            this.url = "http://www.duobeiyun.com";
        }

        this.init();
    }

    public void generateUrl() {
        StringBuffer sb = new StringBuffer();
        sb.append("nickname=").append(this.nickname).append("&").append("partner=").append(this.partner).append("&").append("roomId=").append(this.roomId).append("&").append("timestamp=").append(this.timestamp).append("&").append("uid=").append(this.uid).append("&").append("userRole=").append(this.userRole);
        String pMD5Str = sb.toString() + this.appKey;
        this.sign = EncryptUtils.MD5(pMD5Str);
        this.url = this.baseUrl + sb.append("&").append("sign=").append(this.sign).toString();
        L.i("main", this.url);
    }


    //重写旋转时方法，不销毁activity
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        L.i("main", "onConfigurationChanged::::");
    }


    private void init() {
        this.mWebView = this.findViewById(R.id.webview);
        this.plback = this.findViewById(R.id.portrait_back);
        this.plback.setClickable(true);
        this.tvclassTitle = this.findViewById(R.id.tv_class_title);
        this.tvclassTitle.setText(this.title);
        settings = this.mWebView.getSettings();
        settings.setDefaultTextEncodingName("utf-8");
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setAppCacheEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setUseWideViewPort(true);//关键点
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setDisplayZoomControls(false);
        settings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setBuiltInZoomControls(true); // 设置显示缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        if (Build.VERSION.SDK_INT > 16) {
            settings.setMediaPlaybackRequiresUserGesture(false);
        }

        if (Build.VERSION.SDK_INT >= 21) {
            settings.setMixedContentMode(0);
        }

        if (Build.VERSION.SDK_INT > 18) {
            WebView var10000 = this.mWebView;
            WebView.setWebContentsDebuggingEnabled(true);
        }
        quanping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                System.out.println("切换成横屏");
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                quanping.setVisibility(View.GONE);
                //
                RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) mWebView.getLayoutParams();
                linearParams.height = ScreenUtils.getScreenHeight(getApplicationContext());// 控件的高强制设成20
                mWebView.setLayoutParams(linearParams);
                back_lin.setVisibility(View.VISIBLE);
                toolbar.setVisibility(View.GONE);
                settings.setUseWideViewPort(true);
                settings.setLoadWithOverviewMode(true);
//                DefPlaybackActivity.this.setRequestedOrientation(0);
            }
        });
        back_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) mWebView.getLayoutParams();
                linearParams.height = ScreenUtils.getScreenHeight(getApplicationContext()) - 100;// 控件的高强制设成20
                quanping.setVisibility(View.VISIBLE);
                mWebView.setLayoutParams(linearParams);
                toolbar.setVisibility(View.VISIBLE);
                back_lin.setVisibility(View.GONE);
            }
        });


        if (Build.VERSION.SDK_INT > 16) {
            settings.setMediaPlaybackRequiresUserGesture(false);
        }

        if (Build.VERSION.SDK_INT >= 21) {
            settings.setMixedContentMode(0);
        }

        if (Build.VERSION.SDK_INT > 18) {
            WebView var10000 = this.mWebView;
            WebView.setWebContentsDebuggingEnabled(true);
        }

        this.mWebView.setWebChromeClient(new WebChromeClient() {


        });
        this.mWebView.getSettings().setDomStorageEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        this.mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 在APP内部打开链接，不要调用系统浏览器
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                if (url.startsWith("XXXXXX")) { // 公司官网域名开头
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mWebView.getLayoutParams();
                lp.height = ScreenUtils.getScreenHeight(getApplicationContext()) - 100;
                L.i("main", "===========" + lp.height);
                mWebView.setLayoutParams(lp);
//                }
            }
        });


//
//        this.mWebView.setWebViewClient(new WebViewClient() {
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return false;
//            }
//
//            public void onPageFinished(WebView view, String url) {
//                CookieManager cookieManager = CookieManager.getInstance();
//                if(Build.VERSION.SDK_INT >= 21) {
//                    cookieManager.setAcceptThirdPartyCookies(DefPlaybackActivity.this.mWebView, true);
//                }
//
//                cookieManager.getCookie(url);
//                super.onPageFinished(view, url);
//            }
//
//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                handler.proceed();
//            }
//        });
        this.plback.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!DefPlaybackActivity.this.isFinishing()) {
                    DefPlaybackActivity.this.finish();
                }

            }
        });
        this.mWebView.loadUrl(this.url);
    }


    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        DefPlaybackActivity.this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(DefPlaybackActivity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        mWebView.setVisibility(View.VISIBLE);
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }


    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


    protected void onResume() {
        try {
            this.mWebView.getClass().getMethod("onResume", new Class[0]).invoke(this.mWebView, (Object[]) null);
        } catch (IllegalAccessException var2) {
            var2.printStackTrace();
        } catch (InvocationTargetException var3) {
            var3.printStackTrace();
        } catch (NoSuchMethodException var4) {
            var4.printStackTrace();
        }

        this.mWebView.onResume();
        super.onResume();
    }

    protected void onStart() {
        super.onStart();
    }

    protected void onPause() {
        this.getWindow().clearFlags(128);

        try {
            this.mWebView.getClass().getMethod("onPause", new Class[0]).invoke(this.mWebView, (Object[]) null);
            this.mWebView.onPause();
        } catch (Exception var2) {
            var2.printStackTrace();
        }

        super.onPause();
    }

    protected void onStop() {
        super.onStop();
    }

    protected void onDestroy() {
        this.mWebView.clearCache(true);
        this.mWebView.destroy();
        this.mWebView = null;
        super.onDestroy();
    }


    public static void startDefPlayBackActivity(Activity context, String url) {
        Intent intent = new Intent();
        intent.putExtra("open_url", url);
        intent.setClass(context, DefPlaybackActivity.class);
        context.startActivity(intent);
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:

                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    //竖屏
                    mWebView.goBack();
                    finish();
                } else {
                    //横屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) mWebView.getLayoutParams();
                    linearParams.height = ScreenUtils.getScreenHeight(getApplicationContext()) - 100;// 控件的高强制设成20
                    quanping.setVisibility(View.VISIBLE);
                    mWebView.setLayoutParams(linearParams);
                    toolbar.setVisibility(View.VISIBLE);
                }


//                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
//                if (customView != null) {
////                    hideCustomView();
//                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                } else if (mWebView.canGoBack()) {
//                    mWebView.goBack();
//                } else {
//                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }


}
